package com.ibiaoke.marketing.service;

import com.ibiaoke.common.consts.BusinessDef;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.response.Res;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.common.utils.SmsUtil;
import com.ibiaoke.common.utils.StringUtils;
import com.ibiaoke.customer.dao.CustomerDao;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.marketing.consts.MarketingTypeConsts;
import com.ibiaoke.marketing.dao.CouponReceiveDao;
import com.ibiaoke.marketing.dao.MarketingDao;
import com.ibiaoke.marketing.dao.ShareCouponRelDao;
import com.ibiaoke.marketing.dao.ShareUserRelDao;
import com.ibiaoke.marketing.entity.CouponReceive;
import com.ibiaoke.marketing.entity.Marketing;
import com.ibiaoke.marketing.entity.ShareCouponRel;
import com.ibiaoke.marketing.entity.ShareUserRel;
import com.ibiaoke.marketing.entity.vo.CouponReceiveVO;
import com.ibiaoke.marketing.utils.MarketingUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 用户分享service
 */
@Service
public class ShareUserRelServiceImpl implements ShareUserRelService {

    private static final Logger logger = LogManager.getLogger(ShareUserRelServiceImpl.class);

    @Autowired
    private MarketingDao marketingDao;
    @Autowired
    private ShareUserRelDao shareUserRelDao;
    @Autowired
    private CouponReceiveService couponReceiveService;
    @Autowired
    private CouponReceiveDao couponReceiveDao;
    @Autowired
    private ShareCouponRelDao shareCouponRelDao;
    @Autowired
    private CustomerDao customerDao;

    /**
     * 用户分享
     *
     * @param userId
     * @return
     */
    @Override
    public Res share(Integer userId) {
        Res res = Res.create();
        AssertUtils.notNull(userId, "用户id不能为空");
        List<Marketing> marketings = marketingDao.listValidMarketing(MarketingTypeConsts.SHARE);
        AssertUtils.notEmpty(marketings, "暂无分享活动进行");

        Marketing marketing = marketings.get(0);

        long count = shareUserRelDao.countShareUserRel(marketing.getMarketingId(), userId);
        if (count <= 0) {
            ShareUserRel shareUserRel = new ShareUserRel();
            shareUserRel.setMarketingId(marketing.getMarketingId());
            shareUserRel.setUserId(userId);
            shareUserRel.setCreateTime(new Date());
            shareUserRel.setUpdateTime(new Date());
            shareUserRelDao.insert(shareUserRel);
        }
        ShareUserRel shareUserRel = shareUserRelDao.getShareUserRel(marketing.getMarketingId(), userId);

        long totalReceiveCount = couponReceiveDao.countCoupon(null, marketing.getCouponId(),
                BusinessDef.SHARE, shareUserRel.getId());

        res.addResponse("totalReceiveCount", totalReceiveCount);
        res.addResponse("shareUserRel", shareUserRel);

        return res;
    }

    /**
     * 领取分享优惠券
     *
     * @param receiveUserId  领取人id
     * @param shareUserRelId 用户分享id
     * @return
     */
    @Override
    public Res receiveShareCoupon(Integer receiveUserId, Integer shareUserRelId) {

        Res res = new Res();

        //获取用户分享信息
        AssertUtils.notNull(shareUserRelId, "用户分享ID不能为空");
        ShareUserRel shareUserRel = shareUserRelDao.selectByPrimaryKey(shareUserRelId);
        AssertUtils.notNull(shareUserRel, "用户分享不存在");

        //验证活动
        Integer marketingId = shareUserRel.getMarketingId();
        Marketing marketing = marketingDao.selectByPrimaryKey(marketingId);
        MarketingUtils.validate(marketing);

        //用户领取分享者的优惠券
        Integer couponId = marketing.getCouponId();
        AssertUtils.notNull(couponId, "分享未关联优惠券");
        try {
            int i = couponReceiveService.receiveCouponWithBusiness(receiveUserId, couponId, BusinessDef.SHARE, shareUserRelId);
            if (i > 0) {
                receiveShareUserCoupon(shareUserRel, marketing);
            }
        } catch (ServiceException e) {
            res.addResponse("received", "received");
            res.addResponse("failReceiveReason", e.getLocalizedMessage());
        }
        //查询领取的用户信息
        List<CouponReceive> couponReceives = couponReceiveDao.listCouponReceive(null, couponId, BusinessDef.SHARE, shareUserRelId);
        List<CouponReceiveVO> couponReceiveVOs = couponReceiveService.convert(couponReceives);
        Optional<CouponReceive> receiveOptional = couponReceives.parallelStream()
                .filter(couponReceive -> couponReceive.getUserId().equals(receiveUserId)).findAny();
        CouponReceive myReceiveCoupon = receiveOptional.orElse(null);

        //查询自己领取的信息
        Optional<CouponReceiveVO> couponReceiveVOOpt = couponReceiveVOs.parallelStream().filter(vo -> vo.getUserId().equals(receiveUserId)).findAny();
        CouponReceiveVO couponReceiveVO = couponReceiveVOOpt.orElse(new CouponReceiveVO());

        res.addResponse("couponReceives", couponReceiveVOs);
        res.addResponse("myReceiveCoupon", myReceiveCoupon);
        res.addResponse("myReceiveInfo", couponReceiveVO);
        return res;
    }

    /**
     * 分享人数，达到一定数量时，赠送分享者优惠券
     *
     * @param shareUserRel
     * @param marketing
     */
    private void receiveShareUserCoupon(ShareUserRel shareUserRel, Marketing marketing) {
        Integer shareUserRelId = shareUserRel.getId();

        long totalReceiveCount = couponReceiveDao.countCoupon(null, marketing.getCouponId(), BusinessDef.SHARE, shareUserRelId);

        //分享人数，达到一定数量时，赠送分享者优惠券
        List<ShareCouponRel> shareCouponRels = shareCouponRelDao.listShareCouponRel(marketing.getMarketingId(), null);

        Optional<ShareCouponRel> couponRelOptional = shareCouponRels.parallelStream()
                .filter(shareCouponRel -> shareCouponRel.getNum() == totalReceiveCount).findAny();

        couponRelOptional.ifPresent(shareCouponRel -> {
            try {
                couponReceiveService.receiveCouponWithBusiness(shareUserRel.getUserId(),
                        shareCouponRel.getCouponId(), BusinessDef.SHARE, shareUserRelId);

                //发送短信通知
                Customer customer = customerDao.selectByPrimaryKey(shareUserRel.getUserId());
                if (customer != null && StringUtils.isNotEmpty(customer.getCustomerMobile())) {
                    SmsUtil.sendCouponArriveMsgWithTemp(customer.getCustomerMobile());
                }

            } catch (ServiceException e) {
                logger.error("重复领取奖励优惠券", e);
            }
        });
    }


}
